package model

import (
	"gorm.io/gorm/clause"
	"usercenter/utils/errx"
)

func QueryUserById(id int64) *User {
	res := User{}
	GlobalDB.Where("user_id = ?", id).First(&res)
	return &res
}

func QueryUserByEmail(email string) *User {
	res := User{}
	GlobalDB.Where("email = ?", email).First(&res)
	return &res
}

func QueryUserSysByEmail(email string) *UserSys {
	res := UserSys{}
	GlobalDB.Where("email = ?", email).First(&res)
	return &res
}

func InsertUser(user *User) error {
	return GlobalDB.Create(user).Error
}

func UpdateUserByUserId(user *User) error {
	return GlobalDB.Where("user_id = ?", user.UserId).Updates(user).Error
}

func UpdateUserByUserEmail(user *User) error {
	return GlobalDB.Where("email = ?", user.Email).Updates(user).Error
}

func DeleteUser(id int64) error {
	return GlobalDB.Delete(&User{}, "user_id = ?", id).Error
}
func AddProfilePhoto(hex string) error {
	profilePhoto := ProfilePhoto{}

	ctx := GlobalDB.Begin()
	defer func() {
		r := recover()
		if r == nil {
			return
		}
		if err, ok := r.(error); ok {
			panic(err)
		}
	}()

	ctx.Clauses(clause.Locking{Strength: "UPDATE"}).
		First(&profilePhoto, "profile_photo_hash = ?", hex)
	if profilePhoto.Links <= 0 {
		ctx.Create(&ProfilePhoto{
			ProfilePhotoHash: hex,
			Links:            1,
		})
	} else {
		ctx.Updates(&ProfilePhoto{
			ProfilePhotoHash: hex,
			Links:            profilePhoto.Links + 1,
		})
	}
	ctx.Commit()

	return nil
}

func DecProfilePhoto(hex string) error {
	profilePhoto := ProfilePhoto{}

	ctx := GlobalDB.Begin()
	defer func() {
		r := recover()
		if r == nil {
			return
		}
		if err, ok := r.(error); ok {
			panic(err)
		}
	}()

	ctx.Clauses(clause.Locking{Strength: "UPDATE"}).
		First(&profilePhoto, "profile_photo_hash = ?", hex)

	if profilePhoto.Links <= 1 {
		ctx.Delete(&ProfilePhoto{}, "profile_photo_hash = ?", hex)
		ctx.Commit()
		return errx.CtpError(errx.DecError)
	}

	ctx.Updates(&ProfilePhoto{
		ProfilePhotoHash: hex,
		Links:            profilePhoto.Links - 1,
	})
	ctx.Commit()

	return nil
}

func UpdateUserPhoto(userId int64, hex string) error {
	return GlobalDB.Updates(&User{
		UserId:           userId,
		ProfilePhotoHash: hex,
	}).Error
}
